package net.ge.mosq.web.servlet;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 5459895572473274516L;

	protected Log logger = LogFactory.getLog(this.getClass().getName());

	protected <T> Object generateForm(Class<T> clazz, HttpServletRequest request) {
		Object form = null;
		try {

			form = clazz.newInstance();
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
				if (method.getName().startsWith("set") && method.getName().length() > 3 ? StringUtils.isNotBlank(request.getParameter(method.getName().substring(3))) : false)
					method.invoke(form, request.getParameter(method.getName().substring(3)));
			}
		} catch (InstantiationException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute(clazz.getName(), form);
		return form;
	}
}
